import axios from 'axios';
import config from './config';
import store from '@/store/index.ts';
import Message from '@/components/message';

axios.defaults.headers.common['Authorization'] =
  store.state.tokenHead + '' + store.state.token;
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.put['Content-Type'] = 'application/json';

const request = axios.create(config);

// 添加请求拦截器
request.interceptors.request.use(
  function(config) {
    config.headers.Authorization =
      store.state.tokenHead + '' + store.state.token;
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  response => {
    return Promise.resolve(response.data);
  },
  error => {
    const status = error.response.status + '';
    if (status.startsWith('4')) {
      Message.error(`客户端异常，请检查网络状态（errorCode：${status}）`);
    } else if (status.startsWith('5')) {
      Message.error(`服务端异常，请重新发送请求（errorCode：${status}）`);
    }
    return Promise.reject(error);
  }
);

export default request;
